package com.dissertation.action;

import com.dissertation.pojo.Message;
import com.dissertation.service.ExcelService;
import com.dissertation.utils.ExcelUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("excel")
public class ExcelController {

    @Autowired
    ExcelService excelService;


    /**
     * 导入资源Excel文件
     */
    @PostMapping("{assetsName}")
    Message importAssets(@PathVariable String assetsName,@RequestParam MultipartFile file) throws ClassNotFoundException {
        //判断文件是否为空
        if (file == null) return Message.createErr("文件为空,请重新上传");
        //验证文件名是否合格
        if (!ExcelUtil.validateExcel(file.getOriginalFilename())) {
            return Message.createErr("文件必须是excel格式！");
        }
        return Message.createSuc(excelService.assetsImportGuide(assetsName, file));
    }

    /**
     * 导出资源Excel模板
     */
    @GetMapping("template/{assetsName}")
    public Message assetsTemplate(@PathVariable String assetsName, @RequestParam String fileName, HttpServletResponse response) {
        List<String> idList = null;
        Subject subject = SecurityUtils.getSubject();
        excelService.exportAssetsGuide(assetsName,idList,fileName,response,subject);
        return Message.createSuc("导出模板成功");
    }



    @GetMapping("{assetsName}")
    public Message exportAssets(@PathVariable String assetsName,@RequestParam(required = false) String[] ids,@RequestParam String fileName, HttpServletResponse response) throws ClassNotFoundException {
        Subject subject = SecurityUtils.getSubject();
        List<String> idList = null;
        if(ids!=null){
            idList = Arrays.asList(ids);
        }
        return Message.createSuc(excelService.exportAssetsGuide(assetsName,idList,fileName,response,subject));
    }

}
